package com.agileboot.attendance.controller;

import com.agileboot.attendance.domain.record.db.entity.AttendanceRecord;
import com.agileboot.attendance.domain.record.dto.*;
import com.agileboot.attendance.domain.record.service.IAttendanceRecordService;
import com.agileboot.common.core.base.BaseController;
import com.agileboot.common.core.dto.ResponseDTO;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.common.utils.poi.ExportImportService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 考勤记录Controller
 *
 * @author agileboot
 */
@Tag(name = "考勤记录API")
@RestController
@RequestMapping("/attendance/record")
@RequiredArgsConstructor
public class AttendanceRecordController extends BaseController {

    private final IAttendanceRecordService attendanceRecordService;
    private final ExportImportService exportImportService;

    /**
     * 分页查询考勤记录列表
     */
    @Operation(summary = "获取考勤记录列表")
    @PreAuthorize("@permission.has('attendance:record:list')")
    @GetMapping("/list")
    public ResponseDTO<PageDTO<AttendanceRecordDTO>> list(AttendanceRecordQueryDTO queryDTO,
                                          @RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<AttendanceRecord> page = new Page<>(pageNum, pageSize);
        IPage<AttendanceRecordDTO> pageData = attendanceRecordService.page(page, queryDTO);

        // 转换为统一的PageDTO格式
        PageDTO<AttendanceRecordDTO> result = new PageDTO<>();
        result.setRows(pageData.getRecords());
        result.setTotal(pageData.getTotal());
        result.setPageNum(pageData.getCurrent());
        result.setPageSize(pageData.getSize());

        return ResponseDTO.ok(result);
    }

    /**
     * 获取考勤记录详情
     */
    @Operation(summary = "获取考勤记录详情")
    @PreAuthorize("@permission.has('attendance:record:query')")
    @GetMapping("/{recordId}")
    public ResponseDTO<AttendanceRecordDTO> getInfo(@PathVariable Long recordId) {
        AttendanceRecordDTO dto = attendanceRecordService.getInfo(recordId);
        return ResponseDTO.ok(dto);
    }

    /**
     * 新增考勤记录
     */
    @Operation(summary = "新增考勤记录")
    @PreAuthorize("@permission.has('attendance:record:add')")
    @PostMapping
    public ResponseDTO<Boolean> add(@Valid @RequestBody AttendanceRecordDTO recordDTO) {
        boolean result = attendanceRecordService.add(recordDTO);
        return ResponseDTO.ok(result);
    }

    /**
     * 修改考勤记录
     */
    @Operation(summary = "修改考勤记录")
    @PreAuthorize("@permission.has('attendance:record:edit')")
    @PutMapping
    public ResponseDTO<Boolean> update(@Valid @RequestBody AttendanceRecordDTO recordDTO) {
        boolean result = attendanceRecordService.update(recordDTO);
        return ResponseDTO.ok(result);
    }

    /**
     * 删除考勤记录
     */
    @Operation(summary = "删除考勤记录")
    @PreAuthorize("@permission.has('attendance:record:remove')")
    @DeleteMapping("/{recordId}")
    public ResponseDTO<Boolean> delete(@PathVariable Long recordId) {
        boolean result = attendanceRecordService.delete(recordId);
        return ResponseDTO.ok(result);
    }

    /**
     * 员工打卡
     */
    @Operation(summary = "员工打卡")
    @PreAuthorize("@permission.has('attendance:record:check')")
    @PostMapping("/check-in/{employeeId}")
    public ResponseDTO<Boolean> checkIn(@PathVariable Long employeeId) {
        boolean result = attendanceRecordService.checkIn(employeeId);
        return ResponseDTO.ok(result);
    }

    /**
     * 员工签退
     */
    @Operation(summary = "员工签退")
    @PreAuthorize("@permission.has('attendance:record:check')")
    @PostMapping("/check-out/{employeeId}")
    public ResponseDTO<Boolean> checkOut(@PathVariable Long employeeId) {
        boolean result = attendanceRecordService.checkOut(employeeId);
        return ResponseDTO.ok(result);
    }

    /**
     * 高级打卡（支持位置和照片）
     */
    @Operation(summary = "高级打卡")
    @PreAuthorize("@permission.has('attendance:record:check')")
    @PostMapping("/advanced-check")
    public ResponseDTO<Boolean> advancedCheckIn(@Valid @RequestBody CheckInDTO checkInDTO) {
        boolean result = attendanceRecordService.advancedCheckIn(checkInDTO);
        return ResponseDTO.ok(result);
    }

    /**
     * 导出考勤记录
     */
    @Operation(summary = "导出考勤记录")
    @PreAuthorize("@permission.has('attendance:record:export')")
    @GetMapping("/export")
    public ResponseDTO<Void> export(AttendanceRecordQueryDTO queryDTO, HttpServletResponse response) throws IOException {
        List<AttendanceRecordDTO> list = attendanceRecordService.export(queryDTO);
        exportImportService.exportExcel(list, AttendanceRecordDTO.class, response, "考勤记录");
        return ResponseDTO.ok();
    }

    /**
     * 下载考勤记录导入模板
     */
    @Operation(summary = "下载考勤记录导入模板")
    @PreAuthorize("@permission.has('attendance:record:import')")
    @GetMapping("/importTemplate")
    public ResponseDTO<Void> importTemplate(HttpServletResponse response) throws IOException {
        exportImportService.exportTemplateExcel(AttendanceRecordDTO.class, response, "考勤记录导入模板");
        return ResponseDTO.ok();
    }

    /**
     * 导入考勤记录数据
     */
    @Operation(summary = "导入考勤记录数据")
    @PreAuthorize("@permission.has('attendance:record:import')")
    @PostMapping("/importData")
    public ResponseDTO<Boolean> importData(MultipartFile file) throws IOException {
        List<AttendanceRecordDTO> list = exportImportService.importExcel(file, AttendanceRecordDTO.class);
        boolean result = attendanceRecordService.importRecords(list);
        return ResponseDTO.ok(result);
    }

    /**
     * 获取员工月度考勤统计
     */
    @Operation(summary = "获取员工月度考勤统计")
    @PreAuthorize("@permission.has('attendance:record:stats')")
    @GetMapping("/stats/employee/{employeeId}")
    public ResponseDTO<Map<String, Object>> getEmployeeMonthlyStats(
            @PathVariable Long employeeId,
            @RequestParam String yearMonth) {
        Map<String, Object> stats = attendanceRecordService.getMonthlyStatistics(employeeId, yearMonth);
        return ResponseDTO.ok(stats);
    }

    /**
     * 获取部门月度考勤统计
     */
    @Operation(summary = "获取部门月度考勤统计")
    @PreAuthorize("@permission.has('attendance:record:stats')")
    @GetMapping("/stats/dept/{deptId}")
    public ResponseDTO<Map<String, Object>> getDeptMonthlyStats(
            @PathVariable Long deptId,
            @RequestParam String yearMonth) {
        Map<String, Object> stats = attendanceRecordService.getDeptMonthlyStatistics(deptId, yearMonth);
        return ResponseDTO.ok(stats);
    }

    /**
     * 获取员工当天考勤状态
     */
    @Operation(summary = "获取员工当天考勤状态")
    @GetMapping("/status/{employeeId}")
    public ResponseDTO<String> getTodayStatus(@PathVariable Long employeeId) {
        String status = attendanceRecordService.getEmployeeDailyStatus(employeeId, LocalDate.now());
        return ResponseDTO.ok(status);
    }

    /**
     * 获取员工月度考勤日历
     */
    @Operation(summary = "获取员工月度考勤日历")
    @PreAuthorize("@permission.has('attendance:record:list')")
    @GetMapping("/calendar/{employeeId}")
    public ResponseDTO<List<CalendarItemDTO>> getMonthlyCalendar(
            @PathVariable Long employeeId,
            @RequestParam String yearMonth) {
        List<CalendarItemDTO> calendarData = attendanceRecordService.getMonthlyCalendar(employeeId, yearMonth);
        return ResponseDTO.ok(calendarData);
    }

    /**
     * 批量导入考勤记录
     */
    @Operation(summary = "批量导入考勤记录")
    @PreAuthorize("@permission.has('attendance:record:import')")
    @PostMapping("/batchImport")
    public ResponseDTO<Map<String, Object>> batchImport(@Valid @RequestBody BatchImportDTO batchImportDTO) {
        Map<String, Object> result = attendanceRecordService.batchImport(batchImportDTO);
        return ResponseDTO.ok(result);
    }

    /**
     * 从文件路径导入考勤记录
     */
    @Operation(summary = "从文件导入考勤记录")
    @PreAuthorize("@permission.has('attendance:record:import')")
    @PostMapping("/importFromFile")
    public ResponseDTO<Map<String, Object>> importFromFile(
            @RequestParam String filePath,
            @RequestParam String source,
            @RequestParam(required = false, defaultValue = "admin") String operator) {
        Map<String, Object> result = attendanceRecordService.importFromFile(filePath, source, operator);
        return ResponseDTO.ok(result);
    }
}
